//This is a program that implements the fast pwm feature of the mega16 MCU.
//It is intended to generate a square wave of the duty of 50% at OC1A


//ICC-AVR application builder : 2009/7/29 13:59:49
// Target : M16
// Crystal: 16.000Mhz
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>

void port_init(void)
{
 PORTA = 0x00;
 DDRA  = 0xFF;
 PORTB = 0x01;
 DDRB  = 0x1B;
 PORTC = 0x00; 
 DDRC  = 0xFF;
 PORTD = 0x00;
 DDRD  = 0x30;
}

//TIMER1 initialize - prescale:1
// WGM: 7) PWM 10bit fast, TOP=0x03FF
// desired value: 15625Hz
// actual value: 15625.000Hz (0.0%)
void timer1_init(void)
{
 TCCR1B = 0x00; //stop
 TCNT1 = 0x0000; //setup
 
 OCR1A = 0x03FF/2;
 
 TCCR1A = 0x83;
 TCCR1B = 0x09; //start Timer
}

ISR(TIMER1_OVF_vect)
{
 //TIMER1 has overflowed
}

ISR(TIMER1_COMPA_vect)
{
}
//call this routine to initialize all peripherals
void init_devices(void)
{
 //stop errant interrupts until set up
 cli(); //disable all interrupts
 port_init();
 timer1_init();

 MCUCR = 0x00;
 GICR  = 0x00;
 TIMSK = 0x14; //timer interrupt sources
 sei(); //re-enable interrupts
 //all peripherals are now initialized
}

void led_flash()
{
    PORTB |=1<<1;
    _delay_ms(100);
    PORTB &=~(1<<1);
    _delay_ms(100);
}
int main(void)
{
    init_devices();


    while(1)
        led_flash();

    return 0;
}
